<?php

/**
 * EAuthUserIdentity class file.
 *
 * @author Maxim Zemskov <nodge@yandex.ru>
 * @link http://github.com/Nodge/yii-eauth/
 * @license http://www.opensource.org/licenses/bsd-license.php
 */

/**
 * EAuthUserIdentity is a base User Identity class to authenticate with EAuth.
 *
 * @package application.extensions.eauth
 */
class EAuthUserIdentity extends CUserIdentity {

    const ERROR_NOT_AUTHENTICATED = 3;

    /**
     * @var EAuthServiceBase the authorization service instance.
     */
    protected $service;

    /**
     * @var string the unique identifier for the identity.
     */
    private $id;

    /**
     * @var string the display name for the identity.
     */
    protected $birthday;
    protected $gender;
    protected $name;
    protected $firstname;
    protected $email;
    public $username;
    protected $lastname;
    protected $url;

    /**
     * Constructor.
     *
     * @param EAuthServiceBase $service the authorization service instance.
     */
    public function __construct($service) {
        $this->service = $service;
    }

    /**
     * Authenticates a user based on {@link service}.
     * This method is required by {@link IUserIdentity}.
     *
     * @return boolean whether authentication succeeds.
     */
    public function authenticate() {

        if ($this->service->isAuthenticated) {



            $this->id = $this->service->id;
            $this->name = $this->service->getAttribute('name');
            $this->email = $this->service->getAttribute('email');
            if ($this->service->serviceName == 'yahoo') {
                $this->lastname = $this->service->getAttribute('login');
                $this->name = $this->service->getAttribute('name');
            } else if ($this->service->serviceName == 'google') {
                $this->name = $this->service->getAttribute('name');
                $this->lastname = $this->service->getAttribute('lastname');
            } else if ($this->service->serviceName == 'facebook') {
                $this->url = $this->service->getAttribute('url');
                $this->birthday = $this->service->getAttribute('');
                $this->gender = $this->service->getAttribute('gender');
            } else if ($this->service->serviceName == 'google-oauth') {
                $this->url = $this->service->getAttribute('url');
                $this->name = $this->service->getAttribute('name');
                $this->gender = $this->service->getAttribute('gender');
            }
            //  echo var_dump($this->service);die();


            $email = strtolower($this->email);
            if (strpos($email, '@') !== false) {
                $user = User::model()->find('LOWER(email)=?', array($email));
            }
            if ($user) {
                Yii::app()->user->setFlash('login', 0);
                $this->id = $user->user_id;
                $this->username = $user->username;
                if (Yii::app()->user->allowAutoLogin) {
                    $autoLoginToken = sha1(uniqid(mt_rand(), true));
                    $this->setState('autoLoginToken', $autoLoginToken);
                    $connection = Yii::app()->db;
                    //delete old keys
                    $command = $connection->createCommand('DELETE FROM {{autologin_tokens}} WHERE user_id=:user_id');
                    $command->bindValue(':user_id', $user->user_id, PDO::PARAM_STR);
                    $command->execute();
                    //set new
                    $command = $connection->createCommand('INSERT INTO {{autologin_tokens}}(user_id,token) VALUES(:user_id,:token)');
                    $command->bindValue(':user_id', $user->user_id, PDO::PARAM_STR);
                    $command->bindValue(':token', $autoLoginToken, PDO::PARAM_STR);
                    $command->execute();
                }
                $user->recent_login = time();
                $user->save();
            } else {
                $usernew = new User();
                $geo = GetEGeoIP();
                $usernew->username = $this->email;
                $usernew->email = $this->email;
                $usernew->display_name = $this->name;
                $usernew->password = $this->id;
                $usernew->user_url = ($this->url) ? $this->url : " ";


                $usernew->scenario = 'create';
                if ($usernew->save()) {
                    $AuthAssignment = new AuthAssignment();
                    $AuthAssignment->itemname = 'Guest';
                    $AuthAssignment->userid = $usernew->user_id;
                    $AuthAssignment->scenario = 'create';
                    $AuthAssignment->save();
                    $UserAddresses = new UserAddresses();
                    $UserAddresses->uid = $usernew->user_id;
                    $UserAddresses->phone = ' ';
                    $UserAddresses->street1 = ' ';
                    $UserAddresses->postal_code = ' ';
                    $UserAddresses->country = $geo['country_code'];
                    $UserAddresses->city = $geo['city'];
                    $UserAddresses->created = time();


                    if ($UserAddresses->save()) {

                        $this->id = $usernew->user_id;
                        $this->username = $usernew->username;
                        $user = User::model()->findByPk($this->id);
                        if (Yii::app()->user->allowAutoLogin) {
                            $autoLoginToken = sha1(uniqid(mt_rand(), true));
                            $this->setState('autoLoginToken', $autoLoginToken);
                            $connection = Yii::app()->db;
                            //delete old keys
                            $command = $connection->createCommand('DELETE FROM {{autologin_tokens}} WHERE user_id=:user_id');
                            $command->bindValue(':user_id', $usernew->user_id, PDO::PARAM_STR);
                            $command->execute();
                            //set new
                            $command = $connection->createCommand('INSERT INTO {{autologin_tokens}}(user_id,token) VALUES(:user_id,:token)');
                            $command->bindValue(':user_id', $usernew->user_id, PDO::PARAM_STR);
                            $command->bindValue(':token', $autoLoginToken, PDO::PARAM_STR);
                            $command->execute();
                        }
                        $user->recent_login = time();
                        $user->save();
                    }
                }
            }

//            $this->setState('id', $this->id);
//            $this->setState('name', $this->name);
//            $this->setState('service', $this->service->serviceName);
            //You can save all given attributes in session.
            $attributes = $this->service->getAttributes();
            $session = Yii::app()->session;
            $session['eauth_attributes'][$this->service->serviceName] = $attributes;

            $this->errorCode = self::ERROR_NONE;
        } else {
            $this->errorCode = self::ERROR_NOT_AUTHENTICATED;
        }
        unset($user);
        return !$this->errorCode;
    }

    /**
     * Returns the unique identifier for the identity.
     * This method is required by {@link IUserIdentity}.
     *
     * @return string the unique identifier for the identity.
     */
    public function getId() {
        return $this->id;
    }

    /**
     * Returns the display name for the identity.
     * This method is required by {@link IUserIdentity}.
     *
     * @return string the display name for the identity.
     */
    public function getFirstname() {
        return $this->firstname;
    }

    public function getLastname() {
        return $this->Lastname;
    }

    public function getEmail() {
        return $this->email;
    }

    public function getUsername() {
        return $this->email;
    }

    public function getBirthday() {
        return $this->birthday;
    }

    public function getGender() {
        return $this->gender;
    }

    public function GetUrl() {
        return $this->url;
    }

}
